import TableList from '@/components/Table';
import service from '@/services';
import { ActionType } from '@ant-design/pro-components';
import { useCallback, useMemo, useRef } from 'react';
import UpdateModal from './components/updateModal';
import { getTableFieldsList } from './config/table';
import listConfig from './json/list.json';

export default () => {
  const tableActionRef = useRef<ActionType>(null);
  const updateModalRef = useRef() as any;
  const paramsRef = useRef<Record<string, any>>({});

  const getList = async (params: any) => {
    paramsRef.current = params;
    try {
      const { current, pageSize, ...rest } = params;
      const apiParams = {
        current,
        pageSize,
        ...rest,
      };
      const result = await service.code.list(apiParams);
      return {
        data: result.data.list || [],
        total: result.data.pagination.total || 0,
      };
    } catch (error) {
      console.error('获取数据失败:', error);
      return {
        data: [],
        total: 0,
      };
    }
  };

  const onModal = (record: any, type: string) => {
    if (type === 'update') {
      updateModalRef.current.handleOpen(record);
    }
  };

  // 验证并处理字段配置
  const validatedFields = useMemo(() => {
    // 确保 listConfig 是数组
    if (!Array.isArray(listConfig)) {
      console.error('listConfig 不是数组:', listConfig);
      return [];
    }

    // 验证每个字段的必要属性
    const validFields = listConfig.filter((field: any) => {
      if (!field || typeof field !== 'object') {
        console.warn('无效的字段配置:', field);
        return false;
      }
      if (!field.dataIndex) {
        console.warn('字段缺少 dataIndex:', field);
        return false;
      }
      return true;
    });

    console.log('验证后的字段配置:', validFields);
    return validFields;
  }, []);

  const listFields = useMemo(() => {
    if (validatedFields.length === 0) {
      console.warn('没有有效的字段配置');
      return [];
    }

    try {
      return getTableFieldsList(validatedFields, { onModal });
    } catch (error) {
      console.error('处理字段配置失败:', error);
      return [];
    }
  }, [validatedFields, onModal]);

  const toolBarRender = useCallback(() => {
    return [];
  }, []);

  // 如果没有有效的字段配置，显示错误信息
  if (validatedFields.length === 0) {
    return (
      <div style={{ padding: '20px', textAlign: 'center' }}>
        <p key="error-title">字段配置加载失败，请检查配置文件</p>
        <p key="error-config">当前配置: {JSON.stringify(listConfig)}</p>
      </div>
    );
  }

  return (
    <>
      <TableList
        toolBarRender={toolBarRender}
        rowKey={'id'}
        fields={listFields}
        rowSelection={false}
        getDataSource={getList}
        actionRef={tableActionRef}
      />
      <UpdateModal
        ref={updateModalRef}
        title="编辑兑换码"
        onSubmit={() => {
          tableActionRef.current?.reload();
        }}
        onCancel={() => {}}
      />
    </>
  );
};
